<template>
  <div class="goods-inventory">
    <div class="card goods-inventory__header">
      <el-form inline>
        <el-form-item label="物品类型">
          <el-cascader
            v-model="params.goodsTypeId"
            :options="goodsTypeOptions"
            :props="{ value: 'id', label: 'name' }"
            clearable
          />
        </el-form-item>
        <el-form-item label="是否有库存">
          <el-select
            v-model="params.isHaveStock"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="item in selectOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button
            size="medium"
            type="danger"
            @click="handleReset"
          >重置</el-button>

          <el-button
            size="medium"
            type="primary"
            @click="handleSearch"
          >查询</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="card goods-inventory__content">
      <el-table
        v-loading="loading"
        :data="list"
        border
        stripe
      >
        <el-table-column
          label="物品类型"
          prop="goodsType.name"
          align="center"
        />

        <el-table-column
          label="库存数"
          prop="quantity"
          align="center"
        >
          <template v-slot="{ row }">
            {{ row.quantity }}{{ row?.goodsType.goods_type_main_unit.name }}
          </template>
        </el-table-column>

        <el-table-column
          label="主计量单位"
          prop="goodsType.goods_type_main_unit.name"
          align="center"
        />

        <el-table-column
          label="辅助计量单位数量"
          prop="quantity"
          align="center"
        >
          <template v-slot="{ row }">
            <el-button
              v-if="row.goodsTypeUnit.length > 0"
              type="text"
              @click="handleOpenDialog(row)"
            >查看</el-button>

            <span v-else>-</span>
          </template>
        </el-table-column>

        <el-table-column
          label="是否有库存"
          prop="quantity"
          align="center"
        >
          <template v-slot="{ row }">
            <el-tag v-if="row.quantity > 0" type="primary">有库存</el-tag>
            <el-tag v-else type="danger">无库存</el-tag>
          </template>
        </el-table-column>

        <el-table-column
          label="变更时间"
          prop="updated_at"
          align="center"
        >
          <template v-slot="{ row }">
            {{ timeFormat(row.updated_at) }}
          </template>
        </el-table-column>

        <el-table-column
          label="操作"
          align="center"
        >
          <template v-slot="{ row }">
            <el-button type="text" @click="handleOpenCreateDialog(row)">库存调整</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="goods-inventory__content__pagination">
        <Pagination
          style="margin-top: 0; padding: 0;"
          :total="total"
          :limit="params.paginate"
          @pagination="pagination"
        />
      </div>
    </div>

    <AuxiliaryUnitWithQuantityDialog
      :visible.sync="visible"
      :quantity-info="quantityInfo"
      :quantity="currentGoodsQuantity"
      :main-unit="currentMainUnit"
    />

    <CreateInventoryAdjustDialog
      ref="createInventoryAdjustDialogRef"
      :visible.sync="createDialogVisible"
      :inventory-info="currentInventory"
      :loading="createDialogConfirmLoading"
      @confirm="handleCreateInventoryAdjustConfirm"
    />
  </div>
</template>
<script>
import { getGoodsType, getInventoryInfo, createInventoryAdjust } from '@/api/officeSuppliesManagement'
import dayjs from 'dayjs'
import Pagination from '@/components/Pagination/index.vue'
import AuxiliaryUnitWithQuantityDialog from '@/views/officeSuppliesManagement/components/AuxiliaryUnitWithQuantityDialog.vue'
import CreateInventoryAdjustDialog
from '@/views/officeSuppliesManagement/components/goodsInventory/CreateInventoryAdjustDialog.vue'
import { sleep } from '@/utils'
export default {
  name: '',
  components: {
    Pagination,
    AuxiliaryUnitWithQuantityDialog,
    CreateInventoryAdjustDialog
  },
  data() {
    return {
      list: [],
      params: {
        page: 1,
        paginate: 10,
        isHaveStock: null,
        goodsTypeId: null
      },
      total: 0,
      loading: false,
      selectOptions: [
        { value: '0', label: '无库存' },
        { value: '1', label: '有库存' }
      ],
      goodsTypeOptions: [],
      visible: false,
      quantityInfo: [],
      currentGoodsQuantity: 0,
      currentMainUnit: '',
      createDialogVisible: false,
      currentInventory: null,
      createDialogConfirmLoading: false
    }
  },
  created() {
    this.getInventoryInfo()
    this.getGoodsType()
  },
  methods: {
    async getInventoryInfo() {
      this.loading = true
      try {
        const res = await getInventoryInfo(this.generateParams())
        console.log('res --------->', res)
        this.list = res.data
        this.total = res.meta.total
      } catch (error) {
        console.log('error --------->', error)
        this.$message.error(error?.response?.data?.message || '信息获取失败')
      } finally {
        await sleep()
        this.loading = false
      }
    },

    generateParams() {
      const len = this.params.goodsTypeId?.length
      return {
        ...this.params,
        goodsTypeId: len > 0 ? this.params.goodsTypeId[len - 1] : null
      }
    },

    async getGoodsType() {
      try {
        const res = await getGoodsType()
        this.goodsTypeOptions = res.data
      } catch (error) {
        throw new Error(error?.response?.data?.message || '信息获取失败')
      }
    },

    timeFormat(t) {
      return dayjs(t).format('YYYY-MM-DD HH:mm:ss')
    },

    pagination(page) {
      this.params.page = page.page
      this.params.paginate = page.limit
      this.getInventoryInfo()
    },

    handleSearch() {
      this.params.page = 1
      this.getInventoryInfo()
    },

    handleReset() {
      this.params = this.$options.data().params
      this.getInventoryInfo()
    },

    handleOpenDialog(row) {
      this.quantityInfo = row.goodsTypeUnit
      this.currentGoodsQuantity = row.quantity
      this.currentMainUnit = row.goodsType.goods_type_main_unit?.name
      this.visible = true
    },

    handleOpenCreateDialog(row) {
      console.log('row --------->', row)
      this.currentInventory = row
      this.createDialogVisible = true
      this.$nextTick(() => {
        this.$refs.createInventoryAdjustDialogRef.resetFields()
      })
    },

    handleCreateInventoryAdjustConfirm(e) {
      console.log('e --------->', e)
      this.createInventoryAdjust(e)
    },

    async createInventoryAdjust(params) {
      this.createDialogConfirmLoading = true
      try {
        const res = await createInventoryAdjust(params)
        this.$message.success('创建成功')
        this.createDialogVisible = false
      } catch (error) {
        this.$message.error(error?.response?.data?.message || '创建失败')
      } finally {
        this.createDialogConfirmLoading = false
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.goods-inventory {
  padding: 20px;

  &__header {
    ::v-deep(.el-form-item) {
      margin-bottom: 0;
      margin-right: 20px;
    }
  }

  &__content {

    &__pagination {
      margin-top: 20px;
      display: flex;
      justify-content: end;
    }
  }

  .card {
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;
    margin-bottom: 20px;
  }
}
</style>
